package com.drool.mediaplayer;


import com.drool.mediaplayer.Database.MediaFilesDB;
import com.drool.mediaplayer.Database.MediaFilesDBHelper;
import com.drool.mediaplayer.Database.WritableDatabase;
import com.drool.mediaplayer.Database.MediaFilesDB.*;
import com.drool.mediaplayer.Extracter.AudioInfoExtracter;
import com.drool.mediaplayer.Extracter.VideoInfoExtracter;
import com.drool.mediaplayer.services.DroolService;
import com.drool.mediaplayer.services.IRemoteInterface;
import com.drool.mediaplayer.Interfaces.IRemoteCallback;
import com.drool.mediaplayer.Interfaces.INowPlayingCallback;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.net.Uri.Builder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.provider.MediaStore.Video;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.MediaController.MediaPlayerControl;
import android.widget.SeekBar.OnSeekBarChangeListener;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.text.SimpleDateFormat;
import java.lang.Math.*;


public class MediaPlayerActivity extends Activity {
	Bundle extras;
	private static final String TAG = "Drool:MediaPlayerActivity";
	IRemoteInterface mService = null;
	boolean connected = false;
	ServiceConnection mConnection = null;
	private Handler mHandler = new Handler();
	private int mProgressStatus = 0;
	private INowPlayingCallback mSeekCallback = null;
	private Runnable mUpdateTicker;
	private Playlist pl;
	
	public static final String DATA1 = "Data1";
	public static final String DATA = "Data";
	public static final String TYPE = "Type";
	public static final String SONG = "Song";
	public static final String VIDEO = "Video";
	
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		Log.i(TAG, "Stop() called");
		super.onStop();
		if (connected){
			if (pl!= null && pl.isPlaylistCursorOpened())
			{	
				List<String> list = new ArrayList<String> ();
				
				//list.add("One");
				//list.add("two");
				
				try {
					//list = ;
					Cursor c = pl.getPlaylist();
					//send the playlist in a sequential mode.
					//shuffle is implemented in the service itself
					//if (mService.getPlaylistItems().isEmpty()){
					c.moveToFirst();
					while (!c.isAfterLast()){
						list.add(c.getString(1));
						c.moveToNext();
						}
					/*
					}
					else{
						
					}*/
					
					mService.setPlaylistItems(list);
					mService.setPlaylistController(DroolService.PLAYLIST_CONTROLLER_SERVICE);

					mService.setCurrentSongId(pl.getCurrentSongId());
					
					
					//c.close();
					
				} catch (PlaylistException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
				pl.closePlaylist();
			}
			unbindService(mConnection);
			mConnection = null;
			mService = null;
			Log.i(TAG, "Unbound");
		}
		SharedPreferences settings = getSharedPreferences(MyPreferences.PREFERENCE_NAME,0);
		Log.i(TAG, "mpsate " + settings.getString(MyPreferences.MPSTATE, "DEF"));
		if (!settings.getString(MyPreferences.MPSTATE, "DEF").equals(MyPreferences.MPSTATE_VALUE_PLAYING)){
			Intent intent = new Intent("com.drool.mediaplayer.services.DroolService");
		    stopService(intent);
		    Log.i(TAG, "Stopping service");
		}
		
		
	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		Log.i(TAG, "Start called connected = " + connected);
		
		super.onStart();
	}
	
	

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		Log.i(TAG, "onNewIntent called");
		super.onNewIntent(intent);
		
		extras = intent.getExtras();
		
		
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		Log.i(TAG, "OnCreate called");
		
		setContentView(R.layout.laymediaplayer);
		
		Uri video = Video.Media.EXTERNAL_CONTENT_URI;
		Uri audio = Audio.Media.EXTERNAL_CONTENT_URI;
		
			//uBuilder.appendEncodedPath(mCursorImages2.getString(0)).build();
		VideoView vv = (VideoView) findViewById(R.id.player);
	    MediaController mc = new MediaController(this);
	    
		/*
	    final MediaPlayerSurfaceView mps = new MediaPlayerSurfaceView(getApplicationContext());
	    LinearLayout ll = (LinearLayout)findViewById(R.id.LinearLayout01);
	    ll.addView(mps);
	    */
	    
		extras = getIntent().getExtras();
		
		if (extras.isEmpty()){
			Log.i(TAG, "extras empty");
		}
		
		if (extras.getString(TYPE).equals(VIDEO)){
			Builder uBuilder = video.buildUpon();
			Uri myVideo = uBuilder.appendPath(extras.getString(DATA)).build();
			Log.i("Drool Player", myVideo.toString());
			
			//mc.show();
		    vv.setMediaController(mc);
		    vv.setVideoURI(myVideo);
		    //vv.setVideoURI(Uri.parse("http://www.youtube.com/watch?v=zmU27jICxUU"));
		    
		    updateNumTimesPlayed(extras.getString(DATA), "Video");
		    vv.start();
		    
		    vv.setBackgroundDrawable(null);
		    
		    mc.show();
		    mc.setAnchorView(vv);
			
			//MediaPlayer mp = new MediaPlayer();
		    
		
			/*
			mp.setScreenOnWhilePlaying(true);
			try{				
				mp.setDataSource(this,myVideo);
				//mp.setDisplay(holder);
				mp.prepare();				
				mp.start();
				
			}catch (Exception e){
				Log.e("player", "Error",e);
			}
			
			*/
			//mps.startPlayback(this, myVideo);
		}
		
		if (extras.getString(TYPE).equals(SONG)){
			Cursor albumCursor;
			Uri album = Audio.Albums.EXTERNAL_CONTENT_URI;
			
			Builder uBuilder = audio.buildUpon();
			Uri myAudio = uBuilder.appendPath(extras.getString(DATA)).build();
			Log.i("Drool Player", myAudio.toString());
			
			Button but = (Button)findViewById(R.id.StopBut);
			but.setEnabled(false);
			but = (Button)findViewById(R.id.FwdBut);
			but.setEnabled(false);
			but = (Button)findViewById(R.id.rewBut);
			but.setEnabled(false);

			
			
			//BitmapDrawable bmp = new BitmapDrawable(new Resources(), extras.getString("Data1"));
			
			//vv.setVisibility(vv.INVISIBLE);
			//vv.setBackgroundResource(R.drawable.icon);
			
			/* commenting out to test service
		    vv.setMediaController(mc);		   
		    vv.setVideoURI(myAudio);
		    
		    updateNumTimesPlayed(extras.getString("Data"), "Audio");
		    
		    vv.start();
		    
		    
		    
		    mc.show();
		    LinearLayout l = (LinearLayout)findViewById(R.id.LinearLayout01);
		    
		    mc.setAnchorView(l);
		    */
			
			albumCursor = managedQuery(album, new String[] {
					Audio.Albums._ID, Audio.Albums.ALBUM, Audio.Albums.ALBUM_ART},
					Audio.Albums._ID + "=" + extras.getString(DATA1) , null, null);
			startManagingCursor(albumCursor);
			
			if (albumCursor.getCount() > 0){
				albumCursor.moveToFirst();
				
				if (albumCursor.getString(2) != null){
					BitmapDrawable bmp = new BitmapDrawable(albumCursor.getString(2));
					vv.setBackgroundDrawable(bmp);
				}
				else{
					vv.setBackgroundResource(R.drawable.delta);
				}
					
				//vv.setVisibility(vv.INVISIBLE);
				
			}
			albumCursor.close();
			
			vv.setEnabled(true);
			
			vv.setOnLongClickListener(new OnLongClickListener() {

				@Override
				public boolean onLongClick(View arg0) {
					// TODO Auto-generated method stub
					Log.i(TAG, "Long click recvd");
					return true;
				}
				
			});
			
			vv.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					Log.i(TAG, "click recvd");
				}
				
			});
			
			//load playlist
			SharedPreferences settings = getSharedPreferences(MyPreferences.PREFERENCE_NAME,0);
			/*
			SharedPreferences.Editor prefEditor = settings.edit();
			prefEditor.putString(MyPreferences.MPSTATE, MyPreferences.MPSTATE_VALUE_PLAYING);
			prefEditor.commit();
			*/
			//Playlist pl = null;
			Log.i(TAG, "settings Playlist " + settings.getLong(MyPreferences.ACTIVE_PLAYLIST, -1));
			if (settings.getLong(MyPreferences.ACTIVE_PLAYLIST, -1) == -1){
				pl = new Playlist(Playlist.PLAYLIST_TYPE_NEW, MediaPlayerActivity.this, "Now Playing");
				Log.i(TAG, "Creating new playlist");
			}else{
				pl = new Playlist(settings.getLong(MyPreferences.ACTIVE_PLAYLIST, -1), MediaPlayerActivity.this);
			}
			if (pl.getActivePlaylist() == -1){
				Log.i(TAG, "No active playlist could be attached");
			}
			else{
				SharedPreferences.Editor prefEditor = settings.edit();
				prefEditor.putLong(MyPreferences.ACTIVE_PLAYLIST, pl.getActivePlaylist());					
				prefEditor.commit();
			}
			switch (settings.getInt(MyPreferences.SHUFFLE_STATE, -1)){
				case MyPreferences.SHUFFLE_STATE_VALUE_OFF:
					pl.setShuffle(Playlist.PLAYLIST_SHUFFLE_OFF);
					break;
				case MyPreferences.SHUFFLE_STATE_VALUE_ON:
					pl.setShuffle(Playlist.PLAYLIST_SHUFFLE_ON);
					break;	
				default:
					pl.setShuffle(Playlist.PLAYLIST_SHUFFLE_OFF);
					break;
			}
			
			switch (settings.getInt(MyPreferences.LOOP_STATE, -1)){
				case MyPreferences.LOOP_STATE_VALUE_OFF:
					pl.setLoop(Playlist.PLAYLIST_LOOP_OFF);
					break;
				case MyPreferences.LOOP_STATE_VALUE_ON:
					pl.setLoop(Playlist.PLAYLIST_LOOP_ON);
					break;	
				default:
					pl.setLoop(Playlist.PLAYLIST_LOOP_OFF);
					break;
			}
			
			//pl.setLoop(Playlist.PLAYLIST_LOOP_OFF);
			
			//pl.setCurrentSongId(settings.getInt(MyPreferences.CURRENT_SONG_IN_PLAYLIST, -1));
			
			
			
			but = (Button)findViewById(R.id.FwdBut);						
			but.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					//get the next song to play from playlist
					
					try {
						String song = pl.getNextSong();
						if (song == null){
							Toast.makeText(MediaPlayerActivity.this, "End of playlist!",Toast.LENGTH_LONG).show();
							return;
						}
						mService.setId(song, extras.getString(DATA1));

						updateNumTimesPlayed(song, "Audio");
						
						mService.prepareForPlay();
						mService.play();
						pl.addAlreadyPlayedItem(pl.getCurrentSongId());
						SharedPreferences settings = getSharedPreferences(MyPreferences.PREFERENCE_NAME,0);							
						SharedPreferences.Editor prefEditor = settings.edit();
						prefEditor.putInt(MyPreferences.CURRENT_SONG_IN_PLAYLIST, pl.getCurrentSongId());
						prefEditor.putString(MyPreferences.CURRENT_SONG_ID,song);
						prefEditor.commit();
						
						Cursor albumCursor = managedQuery(Audio.Albums.EXTERNAL_CONTENT_URI, new String[] {
								Audio.Albums._ID, Audio.Albums.ALBUM, Audio.Albums.ALBUM_ART},
								Audio.Albums._ID + "=" + mService.getAlbumId() , null, null);
						startManagingCursor(albumCursor);
						
						if (albumCursor.getCount() > 0){
							albumCursor.moveToFirst();
							VideoView vv = (VideoView)findViewById(R.id.player);
							if (albumCursor.getString(2) != null){
								BitmapDrawable bmp = new BitmapDrawable(albumCursor.getString(2));
								vv.setBackgroundDrawable(bmp);
							}
							else{
								vv.setBackgroundResource(R.drawable.delta);
							}
								
							//vv.setVisibility(vv.INVISIBLE);
							
						}
						albumCursor.close();
						
						int d = mService.getSongDuration();
						SeekBar sk = (SeekBar)findViewById(R.id.SeekBar01);
						sk.setMax(d);
						
						int minDuration = (int) ((d / 1000) / 60);					
						int secDuration = (int) ((d / 1000) % 60);					
						TextView TotalTxt = (TextView)findViewById(R.id.TotalTxt);
						
						Log.i(TAG, intToString(minDuration, 2));
						
						TotalTxt.setText(intToString(minDuration, 2) + ":" + intToString(secDuration, 2));
						
					} catch (RemoteException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (PlaylistException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					//play the song
				}
				
			});
			but = (Button)findViewById(R.id.rewBut);
			but.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					//get the next song to play from playlist
					
					try {
						String song = pl.getPrevSong();
						if (song == null){
							Toast.makeText(MediaPlayerActivity.this, "End of playlist!",Toast.LENGTH_LONG).show();
							return;
						}
						mService.setId(song, extras.getString(DATA1));

						updateNumTimesPlayed(song, "Audio");
						
						mService.prepareForPlay();
						mService.play();
						SharedPreferences settings = getSharedPreferences(MyPreferences.PREFERENCE_NAME,0);							
						SharedPreferences.Editor prefEditor = settings.edit();
						prefEditor.putInt(MyPreferences.CURRENT_SONG_IN_PLAYLIST, pl.getCurrentSongId());
						prefEditor.putString(MyPreferences.CURRENT_SONG_ID, song);
						prefEditor.commit();
						pl.addAlreadyPlayedItem(pl.getCurrentSongId());
						
						Cursor albumCursor = managedQuery(Audio.Albums.EXTERNAL_CONTENT_URI, new String[] {
								Audio.Albums._ID, Audio.Albums.ALBUM, Audio.Albums.ALBUM_ART},
								Audio.Albums._ID + "=" + mService.getAlbumId() , null, null);
						startManagingCursor(albumCursor);
						
						if (albumCursor.getCount() > 0){
							albumCursor.moveToFirst();
							VideoView vv = (VideoView)findViewById(R.id.player);
							if (albumCursor.getString(2) != null){
								BitmapDrawable bmp = new BitmapDrawable(albumCursor.getString(2));
								vv.setBackgroundDrawable(bmp);
							}
							else{
								vv.setBackgroundResource(R.drawable.delta);
							}
								
							//vv.setVisibility(vv.INVISIBLE);
							
						}
						albumCursor.close();
						int d = mService.getSongDuration();
						SeekBar sk = (SeekBar)findViewById(R.id.SeekBar01);
						sk.setMax(d);
						
						int minDuration = (int) ((d / 1000) / 60);					
						int secDuration = (int) ((d / 1000) % 60);					
						TextView TotalTxt = (TextView)findViewById(R.id.TotalTxt);
						
						Log.i(TAG, intToString(minDuration, 2));
						
						TotalTxt.setText(intToString(minDuration, 2) + ":" + intToString(secDuration, 2));
					} catch (RemoteException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (PlaylistException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					//play the song
				}
				
			});

			
			
			
			Log.i(TAG, "Starting the service on create()");
			Intent intent = new Intent("com.drool.mediaplayer.services.DroolService");
		    startService(intent);
		    
			final SeekBar sk = (SeekBar)findViewById(R.id.SeekBar01);
			
		    mConnection = new ServiceConnection(){

				@Override
				public void onServiceConnected(ComponentName arg0, IBinder service) {
					// TODO Auto-generated method stub
					connected = true;
					mService = IRemoteInterface.Stub.asInterface(service);
					
					try {
						Log.i(TAG, mService.getId());
						mService.registerCallback(cb);
						mService.setPlaylistController(DroolService.PLAYLIST_CONTROLLER_GUI);
						Log.i(TAG, "is mp playing " +  mService.isMediaPlayerPlaying());
						Log.i(TAG, "id = id " + extras.getString("Data").equals(mService.getId()));
						
						
						
						if (!mService.isMediaPlayerPlaying() || 
								(mService.isMediaPlayerPlaying() &&
										!extras.getString(DATA).equals(mService.getId()))){
							mService.setId(extras.getString(DATA), extras.getString(DATA1));
							updateNumTimesPlayed(extras.getString(DATA), "Audio");
							
							mService.prepareForPlay();
							mService.play();
							
							SharedPreferences settings = getSharedPreferences(MyPreferences.PREFERENCE_NAME,0);
							SharedPreferences.Editor prefEditor = settings.edit();
							prefEditor.putString(MyPreferences.MPSTATE, MyPreferences.MPSTATE_VALUE_PLAYING);
							prefEditor.commit();
							
							int d = mService.getSongDuration();
							sk.setMax(d);
							
							int minDuration = (int) ((d / 1000) / 60);					
							int secDuration = (int) ((d / 1000) % 60);					
							TextView TotalTxt = (TextView)findViewById(R.id.TotalTxt);
							
							Log.i(TAG, intToString(minDuration, 2));
							
							TotalTxt.setText(intToString(minDuration, 2) + ":" + intToString(secDuration, 2));
							
							if (pl!= null){
								if (!pl.isPlaylistCursorOpened())
									try {
										pl.openPlaylistCursor();
										Log.i(TAG, "Playlist opened");
									} catch (InvalidPlaylistException e2) {
										// TODO Auto-generated catch block
										e2.printStackTrace();
									}
								
								
								try {
									try {										
										long row = pl.updatePlaylist(mService.getId());
										Log.i(TAG, "Playlist updated row = " + Long.toString(row));
										pl.cursorRequery();
										pl.setCurrentSongId(mService.getId(), row);
										Log.i(TAG, "current song set");
									} catch (PlaylistException e) {
										
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
									pl.addAlreadyPlayedItem(pl.getCurrentSongId());
									settings = getSharedPreferences(MyPreferences.PREFERENCE_NAME,0);							
									prefEditor = settings.edit();
									prefEditor.putInt(MyPreferences.CURRENT_SONG_IN_PLAYLIST, pl.getCurrentSongId());
									prefEditor.putString(MyPreferences.CURRENT_SONG_ID, extras.getString(DATA));
									prefEditor.commit();
									
								} catch (NumberFormatException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}
						else{
							Log.i(TAG, "Skipping play");
							SharedPreferences settings = getSharedPreferences(MyPreferences.PREFERENCE_NAME,0);
							SharedPreferences.Editor prefEditor = settings.edit();
							prefEditor.putString(MyPreferences.MPSTATE, MyPreferences.MPSTATE_VALUE_PLAYING);
							prefEditor.commit();
							
							if (pl!= null){
								settings = getSharedPreferences(MyPreferences.PREFERENCE_NAME,0);
								Log.i(TAG, "setting curent song " + Integer.toString(
										settings.getInt(MyPreferences.CURRENT_SONG_IN_PLAYLIST, -1)));
								pl.setCurrentSongId(settings.getInt(MyPreferences.CURRENT_SONG_IN_PLAYLIST, -1));
							}
							
							int d = mService.getSongDuration();
							sk.setMax(d);
							
							int minDuration = (int) ((d / 1000) / 60);					
							int secDuration = (int) ((d / 1000) % 60);					
							TextView TotalTxt = (TextView)findViewById(R.id.TotalTxt);
							TotalTxt.setText(intToString(minDuration, 2) + ":" + intToString(secDuration, 2));
							
							d = mService.getPosition();
							sk.setProgress(d);
							minDuration = (int) ((d / 1000) / 60);					
							secDuration = (int) ((d / 1000) % 60);
							Log.i(TAG, Integer.toString(minDuration) + ":" + Integer.toString(secDuration));
							TextView elapsedTxt = (TextView)findViewById(R.id.elapsedTxt);
							
							elapsedTxt.setText(intToString(minDuration, 2) + ":" + intToString(secDuration, 2));
						}	
						
						setupPlaylistPanel();
						
						Button but = (Button)findViewById(R.id.StopBut);
						but.setEnabled(true);
						but = (Button)findViewById(R.id.FwdBut);
						but.setEnabled(true);
						but = (Button)findViewById(R.id.rewBut);
						but.setEnabled(true);
						
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}	

					
					new Thread(new Runnable() {             
						public void run() {
							seekBarUpdate();							
						}
					}).start();
					
					 // Create runnable for posting    
						mUpdateTicker = new Runnable() {        
						public void run() {
								int i =0;
								//TODO: change the logic of cycling thru
							    TextView txt = (TextView)findViewById(R.id.infoTxt);
							    try {
							    	if (mService != null){
							    		if (txt.getText().equals(mService.getSongName())){
							    			txt.setText(mService.getArtist());
							    		}
							    		else {
							    			if (txt.getText().equals(mService.getArtist())){
							    				txt.setText(mService.getAlbumName());
							    			}
							    			else{
							    				txt.setText(mService.getSongName());
							    			}
							    				
							    		}
							    		
							    	}
							    		
							    //	Log.i(TAG, "i = " + Integer.toString(i));
							    		
								} catch (RemoteException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}    
							}    
						};
					mHandler = new Handler();
					
					new Thread(new Runnable() {

						@Override
						public void run() {
							// This thread updates the song ticker
							tickerUpdate();
						}
						
					}).start();
					
				}

				@Override
				public void onServiceDisconnected(ComponentName arg0) {
					// TODO Auto-generated method stub
					Log.i(TAG, "Service disConnected");
					connected = false;
					mService= null;
				}
		    	
		    };
		    
			bindService(new Intent("com.drool.mediaplayer.services.DroolService"), mConnection, Context.BIND_AUTO_CREATE);
			
			Log.i(TAG, "connected = " + connected);
			
			
			
			sk.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){

				@Override
				public void onProgressChanged(SeekBar arg0, int progress,
						boolean fromUser) {
					// TODO Auto-generated method stub
					TextView elapsedTxt = (TextView)findViewById(R.id.elapsedTxt);
					
					int minDuration = (int) ((progress / 1000) / 60);					
					int secDuration = (int) ((progress / 1000) % 60);					
					elapsedTxt.setText(intToString(minDuration, 2) + ":" + intToString(secDuration, 2));
					
					if (fromUser){
						//advance the playback to that position
						try {
							mService.setPosition(progress);
							
							/*
							new Thread(new Runnable() {             
								public void run() {
									seekBarUpdate();							
								}
							}).start();
							*/
						} catch (RemoteException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
					
				}

				@Override
				public void onStartTrackingTouch(SeekBar arg0) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onStopTrackingTouch(SeekBar arg0) {
					// TODO Auto-generated method stub
					
				}
				
			});
			
			
			
		}
		
		Button stopButt = (Button)findViewById(R.id.StopBut);
		stopButt.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				/*
				if (mConnection != null){
					unbindService(mConnection);
				}
			    Intent intent = new Intent(MediaPlayerActivity.this, DroolService.class);
			    stopService(intent);
			    connected = false;
			    */
				Button but = (Button)view.findViewById(R.id.StopBut);
				
				try {
					if (but.getText().equals("Pause")){
						mService.pause();					
						but.setText("Play");
						SharedPreferences settings = getSharedPreferences(MyPreferences.PREFERENCE_NAME,0);
						SharedPreferences.Editor prefEditor = settings.edit();
						prefEditor.putString(MyPreferences.MPSTATE, MyPreferences.MPSTATE_VALUE_PAUSED);
						prefEditor.commit();
					}
					else{						
						but.setText("Pause");
						new Thread(new Runnable() {             
							public void run() {
								seekBarUpdate();							
							}
						}).start();
						
						mService.play();
						SharedPreferences settings = getSharedPreferences(MyPreferences.PREFERENCE_NAME,0);
						SharedPreferences.Editor prefEditor = settings.edit();
						prefEditor.putString(MyPreferences.MPSTATE, MyPreferences.MPSTATE_VALUE_PLAYING);
						prefEditor.commit();
					}
				} catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		});
	}
	
	private void setupPlaylistPanel(){
		final Button shuffleBut = (Button)findViewById(R.id.shuffleBut);
		
		shuffleBut.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				Log.i(TAG, "Shuffle setting");
				SharedPreferences settings = getSharedPreferences(MyPreferences.PREFERENCE_NAME,0);
				SharedPreferences.Editor prefEditor = settings.edit();
				
				if (pl.getShuffleState() == Playlist.PLAYLIST_SHUFFLE_OFF){						
					pl.setShuffle(Playlist.PLAYLIST_SHUFFLE_ON);
					shuffleBut.setText("S ON");
					prefEditor.putInt(MyPreferences.SHUFFLE_STATE, MyPreferences.SHUFFLE_STATE_VALUE_ON);
					Log.i(TAG, "Shuffle ON");
				}
				else{
					pl.setShuffle(Playlist.PLAYLIST_SHUFFLE_OFF);
					shuffleBut.setText("S OFF");
					prefEditor.putInt(MyPreferences.SHUFFLE_STATE, MyPreferences.SHUFFLE_STATE_VALUE_OFF);
					Log.i(TAG, "Shuffle OFF");
				}
				prefEditor.commit();
				
			}
		});
		
		
		final Button loopBut = (Button)findViewById(R.id.loopBut);
		loopBut.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Log.i(TAG, "loop setting");
				SharedPreferences settings = getSharedPreferences(MyPreferences.PREFERENCE_NAME,0);
				SharedPreferences.Editor prefEditor = settings.edit();
				
				if (pl.getLoopState() == Playlist.PLAYLIST_LOOP_OFF){						
					pl.setLoop(Playlist.PLAYLIST_LOOP_ON);
					loopBut.setText("L ON");
					prefEditor.putInt(MyPreferences.LOOP_STATE, MyPreferences.LOOP_STATE_VALUE_ON);
					Log.i(TAG, "Loop ON");
				}
				else{
					pl.setLoop(Playlist.PLAYLIST_LOOP_OFF);
					loopBut.setText("L OFF");
					prefEditor.putInt(MyPreferences.LOOP_STATE, MyPreferences.LOOP_STATE_VALUE_OFF);
					Log.i(TAG, "Loop OFF");
				}
				prefEditor.commit();
			}
			
			
			
		});
		
		
		try {
			if (!pl.isPlaylistCursorOpened())
				pl.openPlaylistCursor();
			else
				pl.cursorRequery();
			
			final Cursor playlist = pl.getPlaylist();
			startManagingCursor(playlist);
			Log.i(TAG, "playlist returned with " + Integer.toString(playlist.getCount()) + " items");
			
			
			ListView lv = (ListView) findViewById(R.id.slContentList);
			ListAdapter adapter = new SimpleCursorAdapter(
					MediaPlayerActivity.this, R.layout.layplaylistitem,
				    playlist, new String[] {
						MediaFilesDB.PlaylistItems.PLAYLIST_ITEMS_MEDIA_NAME,
					}, new int[] {R.id.txtPlaylistitem1}
			);
			lv.setAdapter(adapter);
			lv.setOnItemLongClickListener(new OnItemLongClickListener(){

				@Override
				public boolean onItemLongClick(
						AdapterView<?> arg0, View arg1,
						int position, long arg3) {
					// TODO Auto-generated method stub
					playlist.moveToPosition(position);
					final String playlistItemId = playlist.getString(0);
					final int playlistItemIndex = playlist.getPosition();
					AlertDialog alertDialog = new AlertDialog.Builder(MediaPlayerActivity.this).create();
				    alertDialog.setTitle("Delete");
				    alertDialog.setMessage("Do you want to remove this song from the playlist?");
				    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				    	//final Cursor playlist = pl.getPlaylist();
				      public void onClick(DialogInterface dialog, int which) {
				    	
				    	  
				    	MediaFilesDBHelper myDBHelper = new MediaFilesDBHelper(MediaPlayerActivity.this);
				    	SQLiteDatabase dbWritable = myDBHelper.getWritableDatabase();	
						
						dbWritable.beginTransaction();
						try{
							dbWritable.delete(MediaFilesDB.PlaylistItems.PLAYLIST_ITEMS_TABLE_NAME,
									MediaFilesDB.PlaylistItems._ID + "= " +
									playlistItemId
									, null);
							dbWritable.setTransactionSuccessful();											
						}catch(Exception e){
							Log.e(TAG, "DB Update failed");
							//TODO code rollback - three inserts have to be rollbacked potentially											
							dbWritable.close();				
						}finally{
							dbWritable.endTransaction();
						}
						dbWritable.close();
						
				    	playlist.requery();						    	
				    	Log.i(TAG, "song deleted " + playlistItemId);
				    	pl.removeFromAlreadyPlayed(playlistItemIndex);
				    	pl.adjustAlreadyPlayed(playlistItemIndex);
				    	
				    	if (playlist.getCount() == 0){
				    		Log.i(TAG, "no more songs in playlist");								    		
				    		pl.setCurrentSongId(-1);
				    	}else {
					    	if (playlistItemIndex ==  pl.getCurrentSongId()){
				    			Log.i(TAG, "Current song deleted");
				    			pl.setCurrentSongId(-1);
				    		}else{
				    			if (playlistItemIndex <  pl.getCurrentSongId()){
				    				pl.setCurrentSongId(pl.getCurrentSongId() - 1);
				    			}
				    		}
				    	}
				    	
				    	
				    
				    	  return;
				    	  
				      } }); 
				    alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
					      public void onClick(DialogInterface dialog, int which) {
					        return;
					      } });
					
				    alertDialog.show();
					return true;
				}
				
			});
			
		} catch (InvalidPlaylistException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (PlaylistException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	private String intToString(int number, int numDigits){
		
		if (numDigits == 2){
			if (number < 10)
				return ("0" + Integer.toString(number));
			else
				return Integer.toString(number);
		}
		else
			return Integer.toString(number);
		
	}
	
	private IRemoteCallback cb = new IRemoteCallback(){

		@Override
		public IBinder asBinder() {
			// TODO Auto-generated method stub
			return null;
		}
		
		@Override
		public void playbackComplete() throws RemoteException {
			// TODO Auto-generated method stub
			Log.i(TAG, "Playback complete");
			SeekBar sk = (SeekBar)findViewById(R.id.SeekBar01);
			sk.setProgress(sk.getMax());
			
			if (pl!=null){
				String song = null;
				try {
					song = pl.getNextSong();
				} catch (PlaylistException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				if (song == null){
					Button but = (Button)findViewById(R.id.StopBut);
					but.setText("Play");
					SharedPreferences settings = getSharedPreferences(MyPreferences.PREFERENCE_NAME,0);
					SharedPreferences.Editor prefEditor = settings.edit();
					prefEditor.putString(MyPreferences.MPSTATE, MyPreferences.MPSTATE_VALUE_STOPPED);
					prefEditor.commit();
					return;
				}
				
				mService.setId(song, extras.getString(DATA1));
				updateNumTimesPlayed(song, "Audio");					
				mService.prepareForPlay();					
				Button but = (Button)findViewById(R.id.StopBut);
				but.setText("Pause");
				new Thread(new Runnable() {             
					public void run() {
						seekBarUpdate();							
					}
				}).start();
				
				mService.play();
					
				SharedPreferences settings = getSharedPreferences(MyPreferences.PREFERENCE_NAME,0);							
				SharedPreferences.Editor prefEditor = settings.edit();
				prefEditor.putInt(MyPreferences.CURRENT_SONG_IN_PLAYLIST, pl.getCurrentSongId());
				prefEditor.putString(MyPreferences.CURRENT_SONG_ID, song);
				prefEditor.commit();
				pl.addAlreadyPlayedItem(pl.getCurrentSongId());
				
				Cursor albumCursor = managedQuery(Audio.Albums.EXTERNAL_CONTENT_URI, new String[] {
						Audio.Albums._ID, Audio.Albums.ALBUM, Audio.Albums.ALBUM_ART},
						Audio.Albums._ID + "=" + mService.getAlbumId() , null, null);
				startManagingCursor(albumCursor);
				
				if (albumCursor.getCount() > 0){
					albumCursor.moveToFirst();
					VideoView vv = (VideoView)findViewById(R.id.player);
					if (albumCursor.getString(2) != null){
						BitmapDrawable bmp = new BitmapDrawable(albumCursor.getString(2));
						vv.setBackgroundDrawable(bmp);
					}
					else{
						vv.setBackgroundResource(R.drawable.delta);
					}
						
					//vv.setVisibility(vv.INVISIBLE);
					
				}
				albumCursor.close();
				int d = mService.getSongDuration();
				sk.setMax(d);
				
				int minDuration = (int) ((d / 1000) / 60);					
				int secDuration = (int) ((d / 1000) % 60);					
				TextView TotalTxt = (TextView)findViewById(R.id.TotalTxt);
				
				Log.i(TAG, intToString(minDuration, 2));
				
				TotalTxt.setText(intToString(minDuration, 2) + ":" + intToString(secDuration, 2));
				
				settings = getSharedPreferences(MyPreferences.PREFERENCE_NAME,0);
				prefEditor = settings.edit();
				prefEditor.putString(MyPreferences.MPSTATE, MyPreferences.MPSTATE_VALUE_PLAYING);
				prefEditor.commit();
				
			}
			
			
			/*
			Button but = (Button)findViewById(R.id.StopBut);
			but.setText("Play");
			
			*/
		}
		

		
		
	};
	
	private void seekBarUpdate(){
		int oldPosition = 0, position = 0;
		//Log.i(TAG, "From inside the thread, before going to while");
		SeekBar sk = (SeekBar)findViewById(R.id.SeekBar01);
		try {
			while (true){
				//Log.i(TAG, this.toString() + " is running");
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (mService != null)
					oldPosition = mService.getPosition();
				else
					break;
				
				if (Math.abs(oldPosition - position) >= 1000){
					position = oldPosition;					
					sk.setProgress(position);
						
				}
			}
			
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();			
		}catch (NullPointerException e1){
			Log.e(TAG, "Service instance no longer valid");
		}
	}
	
	private void tickerUpdate(){
		
		TextView txt = (TextView)findViewById(R.id.infoTxt);
		
		Log.i(TAG, "Ticker updated thread running");
		
		while(true){
			if (mService != null){
				//txt.setText(mService.getArtist());
				mHandler.post(mUpdateTicker);
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			else
				break;
		}
		Log.i(TAG, "Ticker updated thread exiting");
	}
	
	private void updateNumTimesPlayed(String mediaId, String mediaType){
		AudioInfoExtracter aExtracter;
		VideoInfoExtracter vExtracter;
		
		
		if (mediaType.equals("Video")){
			vExtracter  = new VideoInfoExtracter();
			vExtracter.mCursorVideo = managedQuery(vExtracter.mMedia, vExtracter.projection, 
					Audio.Media._ID + " = " + mediaId, null,null);
			Log.i(TAG, Integer.toString(vExtracter.mCursorVideo.getCount()));
			startManagingCursor(vExtracter.mCursorVideo);
			if (vExtracter.mCursorVideo.getCount() == 1){
				vExtracter.mCursorVideo.moveToFirst();
				new WritableDatabase(this).updateNumTimesPlayed(WritableDatabase.VIDEO, 
													vExtracter.mCursorVideo.getString(2));
			}
			vExtracter.mCursorVideo.close();
		}
		else{
			aExtracter  = new AudioInfoExtracter();
			aExtracter.mCursorAudio = managedQuery(aExtracter.mMedia, aExtracter.projection, 
					Audio.Media._ID + " = " + mediaId, null,null);
			Log.i(TAG, Integer.toString(aExtracter.mCursorAudio.getCount()));
			startManagingCursor(aExtracter.mCursorAudio);
			if (aExtracter.mCursorAudio.getCount() == 1){
				aExtracter.mCursorAudio.moveToFirst();
				new WritableDatabase(this).updateNumTimesPlayed(WritableDatabase.AUDIO, 
													aExtracter.mCursorAudio.getString(2));
			}
			aExtracter.mCursorAudio.close();
		}
	}
	
}		

